package edu.ynu.se.xiecheng.achitectureclass.demo.service;

import edu.ynu.se.xiecheng.achitectureclass.common.service.LogicService;
import edu.ynu.se.xiecheng.achitectureclass.demo.dao.UserDao;
import edu.ynu.se.xiecheng.achitectureclass.demo.entity.User;
import edu.ynu.se.xiecheng.achitectureclass.demo.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class UserService extends LogicService<UserDao, User, Long> implements UserDetailsService {

    @Autowired
    private JwtUtil jwtUtil;

    public UserService(@Autowired UserDao dao) {
        super(dao);
    }

    public boolean isUserExists(String username, String password) {
        User user = getDAO().findByUsernameAndPassword(username, password);
        return user != null;
    }

    public String generateToken(String username) {
        return jwtUtil.generateToken(username);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = getDAO().findUserByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("User not found with username: " + username);
        }
        return user;
    }

    public boolean isUsernameExists(String username) {
        User user = getDAO().findUserByUsername(username);
        if (user == null) {
            return false;
        }
        return true;
    }
}